<template>
  <div>
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item prop="name">
        <el-input v-model="dataForm.name" placeholder="模版名称" clearable>
        </el-input>
      </el-form-item>
      <el-form-item prop="type">
        <el-cascader
          expand-trigger="hover"
          :options="options"
          v-model="selectedOptions"
          placeholder="业务模版类型"
          @change="changeWorksheetType"
          clearable
        >
        </el-cascader>
      </el-form-item>
      <el-form-item prop="creatorId">
        <el-select v-model="dataForm.creatorId" placeholder="创建者" clearable>
          <el-option
            v-for="item in adminList"
            :key="item.userId"
            :label="item.name"
            :value="item.userId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="status">
        <el-select clearable v-model="dataForm.status" placeholder="模版状态">
          <el-option :value="1" label="已启用"></el-option>
          <el-option :value="0" label="未启用"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addOrUpdateHandle(0)">新增</el-button>
        <el-button
          type="danger"
          :disabled="dataListSelections.length <= 0"
          @click="deleteHandle()"
          >批量删除</el-button
        >
        <el-button type="info" @click="dataForm = {}">重置</el-button>
        <el-button type="info" @click="refresh">刷新</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据 -->
    <el-table
      :data="dataList"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column prop="name" label="模版名称" width="100">
      </el-table-column>
      <el-table-column prop="sample" label="模版样例图片" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.sample"
            :src="prePath + scope.row.sample"
            style="width: 150px; height: 100px"
            :preview-src-list="[prePath + scope.row.sample]"
          />
          <el-image v-else>
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="业务类型">
        <template slot-scope="scope">
          {{ typeArr.find((res) => res.id === Number(scope.row.type)).name }}
        </template>
      </el-table-column>
      <el-table-column prop="explanation" label="业务填写备注信息">
      </el-table-column>
      <el-table-column prop="creatorName" label="业务创建人员">
      </el-table-column>
      <el-table-column prop="memo" label="备注"> </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success">已启用</el-tag>
          <el-tag v-else type="info">未启用</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" width="200" label="操作">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="primary"
            @click="downloadFile(scope.row)"
            >下载模版</el-button
          >
          <el-button
            v-if="isAuth('feature:repair:update')"
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.id)"
            >修改</el-button
          >

          <el-button
            v-if="isAuth('feature:repair:delete')"
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="page"
      :page-sizes="[5, 10, 20, 50, 100]"
      :page-size="size"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <!-- 新增和修改的弹层 -->
    <el-dialog
      :title="!formData.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible="visible"
      @close="closeForm"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="formData"
        @keyup.enter.native="dataFormSubmit()"
        label-width="100px"
      >
        <el-form-item prop="path" label="上传模版">
          <el-upload
            class="upload-demo"
            :action="prePath + formData.path"
            :http-request="uploadText"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传一个文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item prop="name" label="模版名称">
          <el-input v-model="formData.name" placeholder="模版名称" clearable>
          </el-input>
        </el-form-item>
        <el-form-item prop="sample" label="样例图片">
          <el-upload
            class="avatar-uploader"
            :action="prePath + formData.sample"
            :http-request="uploadImage"
            :show-file-list="false"
          >
            <img
              alt=""
              v-if="formData.sample"
              :src="prePath + formData.sample"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="type" label="模版类型">
          <el-cascader
            expand-trigger="hover"
            :options="options"
            v-model="selectedOptions"
            placeholder="业务模版类型"
            @change="changeWorksheetType"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item prop="explanation" label="填写业务说明">
          <el-input
            type="textarea"
            v-model="formData.explanation"
            placeholder="=业务填写时的注意事项"
          ></el-input>
        </el-form-item>
        <el-form-item prop="memo" label="备注">
          <el-input
            type="textarea"
            v-model="formData.memo"
            placeholder="备注信息"
          ></el-input>
        </el-form-item>
        <el-form-item prop="status" label="模版状态">
          <el-radio v-model="formData.status" :label="1">已启用</el-radio>
          <el-radio v-model="formData.status" :label="0">未启用</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeForm">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit('formData')"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataListSelections: [],
      dataList: [],
      selectedOptions: [],
      // 修改/新增的弹窗数据
      formData: {},
      visible: false,
      // 管理员列表
      adminList: [],
      // 工单类型
      options: [
        {
          value: 1,
          label: '资源申请',
          children: [
            {
              value: 2,
              label: 'VPN申请(本校师生)'
            },
            {
              value: 12,
              label: 'VPN申请(实践基地教师)'
            },
            {
              value: 3,
              label: '入网账号和电子邮箱申请'
            },
            {
              value: 10,
              label: '服务器资源申请'
            },
            {
              value: 11,
              label: '网络域名与网站开通审批'
            }
          ]
        },
        {
          value: 5,
          label: '维修申请',
          children: [
            {
              value: 6,
              label: '网络故障'
            },
            {
              value: 7,
              label: '软件故障'
            },
            {
              value: 8,
              label: '硬件故障'
            }
          ]
        }
      ],
      // 工单类型数组
      typeArr: [
        {
          id: 2,
          name: 'VPN申请(本校师生)'
        },
        {
          id: 12,
          name: 'VPN申请(实践基地教师)'
        },
        {
          id: 3,
          name: '入网账号和电子邮箱申请'
        },
        {
          id: 10,
          name: '服务器资源申请'
        },
        {
          id: 11,
          name: '网络域名与网站开通审批'
        },
        {
          id: 6,
          name: '网络故障'
        },
        {
          id: 7,
          name: '软件故障'
        },
        {
          id: 8,
          name: '硬件故障'
        }
      ],
      dataForm: {
        name: '',
        type: '',
        creatorId: '',
        status: ''
      },
      rules: {
        name: [{ required: true, message: '请输入模版名称', trigger: 'blur' }],
        type: [{ required: true, message: '请输入模版类型', trigger: 'blur' }],
        status: [{ required: true, message: '请选择模版状态', trigger: 'blur' }]
      },
      dataListLoading: false,
      addOrUpdateVisible: false,
      // 模版文件
      fileList: [],
      // 分页
      page: 1,
      size: 10,
      total: 0,
      // 文件前缀路径
      // prePath: 'http://47.109.153.71:8080/sys/file/getFile?filename=',
      prePath: 'https://networker.nsmc.edu.cn/sys/file/getFile?filename=',
      // 判断是否上传完成文件
      OK1: false,
      OK2: false
    }
  },
  methods: {
    getDataList() {
      this.$http({
        url: this.$http.adornUrl(
          'sys/worksheetTemplate/getWorksheetTemplateList'
        ),
        method: 'post',
        data: this.$http.adornData({
          ...this.dataForm,
          page: this.page,
          size: this.size
        })
      }).then(({ data }) => {
        this.dataList = data.data
        this.total = data.total
        this.getAdminList()
      })
    },
    getAdminList() {
      // 获取数据
      this.$http({
        url: this.$http.adornUrl('sys/visitor/getVisitorList'),
        method: 'post',
        data: this.$http.adornData({
          ...this.dataForm,
          type: 1,
          page: this.page,
          size: this.size
        })
      }).then(({ data }) => {
        this.adminList = data.data
      })
    },
    downloadFile(item) {
      this.$http({
        url: this.$http.adornUrl(`/sys/file/getFile?filename=${item.path}`),
        responseType: 'blob'
      }).then(({ data }) => {
        const str = item.name + item.path.substr(item.path.indexOf('.'))
        const blobURL = window.URL.createObjectURL(
          new Blob([data], { type: 'application/octet-stream' })
        )
        const tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', str)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.size = val
      this.page = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.page = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 修改新增弹层
    addOrUpdateHandle(id) {
      this.formData.id = id || 0
      if (this.formData.id) {
        // 修改
        this.$http({
          url: this.$http.adornUrl(
            `sys/worksheetTemplate/selectById/${this.formData.id}`
          ),
          method: 'get'
        }).then(({ data }) => {
          this.formData = data.data
          // 回显工单类型
          this.traverseData(this.options)
        })

        this.visible = true
      } else {
        // 新增
        this.visible = true
      }
    },
    //递归完成回显
    traverseData(data, parentIds = []) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i]
        const ids = [...parentIds, item.value]
        if (this.formData.type === item.value) {
          this.selectedOptions = [...ids] //回显赋值
        }

        if (item.children && item.children.length > 0) {
          this.traverseData(item.children, ids)
        }
      }
    },
    // 确定添加
    dataFormSubmit(ppp) {
      // console.log(this.$store.state.user.id)
      // console.log(this.formData.id)
      this.$refs[ppp].validate((OK) => {
        if (!OK) {
          return false
        } else {
          if (this.formData.id) {
            // 修改
            this.$http({
              url: this.$http.adornUrl(
                'sys/worksheetTemplate/updateWorksheetTemplate'
              ),
              method: 'put',
              data: this.$http.adornData({
                ...this.formData,
                creatorId: this.$store.state.user.id
              })
            }).then(({ data }) => {
              if (data.code === 0) {
                this.$message.success(data.msg)
                this.closeForm()
                this.getDataList()
              } else {
                this.$message.error(data.msg)
              }
            })
          } else {
            if (!this.OK1 || !this.OK2) {
              this.$message.warning('请耐心等待上传完成！')
              return
            }
            this.$http({
              url: this.$http.adornUrl(
                'sys/worksheetTemplate/addWorksheetTemplate'
              ),
              method: 'post',
              data: this.$http.adornData({
                ...this.formData,
                creatorId: this.$store.state.user.id
              })
            }).then(({ data }) => {
              if (data.code === 0) {
                this.$message.success(data.msg)
                this.closeForm()
                this.getDataList()
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        }
      })
    },
    // 关闭
    closeForm() {
      this.visible = false
      this.selectedOptions = []
      this.$refs['formData'].resetFields()
      this.formData = {}
      this.OK1 = false
      this.OK2 = false
    },

    // 选择模版类型
    changeWorksheetType(res) {
      this.formData.type = res[res.length - 1]
    },

    // 上传模版文件
    uploadText(data) {
      let params = new FormData()
      params.append('file', data.file)
      this.$http({
        url: this.$http.adornUrl('sys/worksheetTemplate/upload'),
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data;charset=utf-8'
        },
        data: params
      }).then(({ data }) => {
        console.log(data)
        if (data.code === 1) {
          this.formData.path = data.data
          this.$message.success(data.msg)
          this.OK1 = true
        }
      })
    },
    uploadImage(data) {
      let params = new FormData()
      params.append('file', data.file)
      this.$http({
        url: this.$http.adornUrl('sys/worksheetTemplate/upload'),
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data;charset=utf-8'
        },
        data: params
      }).then(({ data }) => {
        console.log(data)
        if (data.code === 1) {
          this.formData.sample = data.data
          this.$message.success(data.msg)
          this.OK2 = true
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 刷新
    refresh() {
      //this.dataForm = {}
      //this.selectedOptions = []
      this.getDataList()
    },
    // 删除
    deleteHandle(id) {
      let ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id
          })
      this.$confirm(
        `确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          console.log(ids)
          this.$http({
            url: this.$http.adornUrl(
              'sys/worksheetTemplate/deleteWorksheetTemplateByIds'
            ),
            method: 'put',
            params: { ids },
            // 主要是以下四行代码 , 传数组参数
            paramsSerializer: function (params) {
              const ids = params.ids.map((_) => `ids=${_}`).join('&')
              return `${ids}`
            }
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
        .catch(() => {})
    }
  },
  mounted() {
    this.getDataList()
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
